package com.ptt.sqm.session;

import java.lang.reflect.Type;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashSet;
import java.util.Set;
import java.util.SortedSet;
import java.util.TreeSet;

import android.content.Context;
import android.content.SharedPreferences;
import android.util.Log;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.ptt.sqm.model.AssessTran;
import com.ptt.sqm.util.AppUtil;

public class SavedAssessTran {
	// Context
	Context _context;
	private static SharedPreferences prefs;
	private static final Type MAP_TYPE = new TypeToken<AssessTran>() {
	}.getType();

	private static final Type ORDER_TYPE = new TypeToken<LinkedHashSet<String>>() {
	}.getType();

	private static AssessTran myMap;

	public SavedAssessTran(Context _context) {
		super();
		this._context = _context;
		prefs = _context.getSharedPreferences(AppUtil.SAVED_TRAN_ASSESS_PREF, Context.MODE_PRIVATE);
	}

	public static void saveMap(String key, AssessTran tran) {
		SharedPreferences.Editor editor = prefs.edit();

		tran.Lastupdate = new Date();
		editor.putString(key, new Gson().toJson(tran));

		// Create the sorted assess
		LinkedHashSet<String> order = new Gson().fromJson(prefs.getString(AppUtil.SAVED_TRAN_ASSESS_ORDER, null), ORDER_TYPE);
		if (order == null)
			order = new LinkedHashSet<String>();

		if (order.contains(key))
			order.remove(key);

		order.add(key);

		editor.putString(AppUtil.SAVED_TRAN_ASSESS_ORDER, new Gson().toJson(order));

		editor.commit();

		myMap = tran;
	}

	public static AssessTran loadMap(String key) {
		myMap = new Gson().fromJson(prefs.getString(key, null), MAP_TYPE);

		return myMap;
	}

	public static void ClearSavedAssessTran(String key) {
		SharedPreferences.Editor editor = prefs.edit();

		editor.putString(key, null);
		editor.commit();
	}

}
